package com.xbb.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xbb.entity.*;
import com.xbb.service.IAutoconfigService;
import com.xbb.service.IStudentService;
import com.xbb.service.UserService;
import com.xbb.util.Result;
import com.xbb.util.Result1;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 学生（客户）控制层
 * </p>
 *
 * @author Mr xie
 * @since 2020-06-03
 */
@RestController
@RequestMapping("/student")
public class StudentController {

    @Autowired
    IAutoconfigService autoservice;
    @Autowired
    UserService service;
    @Autowired
    IStudentService stuService;

    /**
     * 多条件分页查询，获取所有学生信息
     *咨询经理页面
     * @param studentParam
     * @return
     */
    @RequestMapping("/getStus")
    public Object getStus(StudentParam studentParam) {
        List<StudentParam> list = stuService.getStuList(studentParam);
        studentParam.setPage(null);
        studentParam.setLimit(null);
        List<StudentParam> list2 = stuService.getStuList(studentParam);
        return new Result1(0, "查询成功", list2.size(), list);
    }

    /**
     * 多条件分页查询，获取所有学生信息
     *  咨询师页面
     * @param userParam
     * @param studentParam
     * @param userId
     * @return
     */
    @RequestMapping("/getStuListInZiXunShi")
    public Object getStuListInZiXunShi(UserParam userParam,StudentParam studentParam,Integer userId) {
        userParam.setId(userId);
        System.out.println("11111"+userId);
        List<StudentParam> list = stuService.getStuListInZiXunShi(studentParam);
        studentParam.setPage(null);
        studentParam.setLimit(null);
        List<StudentParam> list2 = stuService.getStuListInZiXunShi(studentParam);
        return new Result1(0, "查询成功", list2.size(), list);
    }

    /**
     * 多条件分页查询，获取所有学生信息
     *  网络咨询师页面
     * @param studentParam
     * @param entryName
     * @return
     */
    @RequestMapping("/getStuListInWangLuoZiXunShi")
    public Object getStuListInWangLuoZiXunShi(UserParam userParam,StudentParam studentParam,String entryName) {
        userParam.setLoginName(entryName);
        System.out.println("11111"+entryName);
        List<StudentParam> list = stuService.getStuListInWangLuoZiXunShi(studentParam);
        studentParam.setPage(null);
        studentParam.setLimit(null);
        List<StudentParam> list2 = stuService.getStuListInWangLuoZiXunShi(studentParam);
        return new Result1(0, "查询成功", list2.size(), list);
    }


    /**
     * 自动分配
     * 添加时判断是否自动分配给用户
     * <p>// 1待分配 , 0已分配
     * 拿到权重最大待分配用户 如果存在添加学生，并且添加成功时修改用户的分配状态为已分配 如果不存在让所有的用户的分配状态全部改为待分配 0:已分配 1：待分配
     *
     * @param s
     * @return
     */
    @SuppressWarnings({"null", "unused"})
    @RequestMapping("/addStu")
    public Object add(@Valid Student s) {
        Autoconfig byId = autoservice.getById(1);
        // 判断是否开启自动分配1：开启0：关闭
        if (byId.getIsAutoconfig() == 1) {
            List<User> getzixunshi1 = service.getZiXunShiByWeight(null);
            System.out.println(getzixunshi1);
            // 获取集合中的属性添加到数组中
            List<String> str1 = new ArrayList<String>();
            List<Integer> str = new ArrayList<Integer>();
            System.out.println("bb");
            for (int i = 0; i < getzixunshi1.size(); i++) {
                str1.add(i, getzixunshi1.get(i).getQiandaoState());
                //判断咨询师是否签到
                if (getzixunshi1.get(i).getQiandaoState().equals("已签到")) {
                    str.add(i, getzixunshi1.get(i).getId());
                } else {
                    str.add(i, 0);
                }
            }
            System.out.println(str);
            System.out.println(str1);
            //判断咨询师存在已打卡
            if (str1.contains("已签到")) {
                //查询待分配的咨询师
                User one2 = service.getOne(new QueryWrapper<User>().eq("is_config", 1).orderByDesc("weight").last("limit 0 , 1"));
                System.out.println(one2);
                //如果没查到待分配，
                if (one2 == null) {
                    service.updateBatchUser(str, 1);
                    //此时咨询师全部为待分配进行行查询
                    User one3 = service.getOne(new QueryWrapper<User>().eq("is_config", 1).orderByDesc("weight").last("limit 0 , 1"));
                    System.out.println(one3);
                    Integer userId3 = one3.getId();
                    s.setUserId(userId3);
                    //添加学生时给学生添加咨询师
                    boolean save = stuService.save(s);
                    if (save) {
                        User u = new User();
                        u.setIsConfig("0");
                        service.update(u, new QueryWrapper<User>().eq("id", userId3));
                        return new Result(0, "添加成功");
                    }
                    return new Result(1, "添加失败");
                } else {
                    Integer userId = one2.getId();
                    s.setUserId(userId);
                    boolean save = stuService.save(s);
                    if (save) {
                        User u = new User();
                        u.setIsConfig("0");
                        //修改咨询师状态为已分配
                        service.update(u, new QueryWrapper<User>().eq("id", userId));
                        return new Result(0, "添加成功");
                    }
                    return new Result(1, "添加失败");
                }
            } else {
                Date date = new Date();
                SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                List<Student> stuName = stuService.getStuName(s);
                if (stuName != null && stuName.size() > 0) {
                    return new Result(2, "添加失败，学生名称不能重复添加");
                }
                s.setCreateTime(sdf.format(date));
                boolean save = stuService.save(s);
                if (save) {
                    return new Result(0, "添加成功");
                }
                return new Result(1, "添加失败");
                //未获取到已打卡的咨询师
            }
        } else {
            List<Student> stuName = stuService.getStuName(s);
            if (stuName != null && stuName.size() > 0) {
                return new Result(2, "添加失败，学生名称不能重复添加");
            }
            Date date = new Date();
            SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            s.setCreateTime(sdf.format(date));
            boolean save = stuService.save(s);
            if (save) {
                return new Result(0, "添加成功");
            }
            return new Result(1, "添加失败");
        }

    }


    /**
     * 一键分配  // 1待分配 , 0已分配
     *
     * @return
     */
    @RequestMapping("/setOnceAuto")
    public Object setOnceAuto() {
        //查询签到用户状态
        QueryWrapper<User> userquery = new QueryWrapper<User>();
        userquery.eq("qiandao_state", "已签到");//已经签到
        //获取咨询师
        List<User> getzixunshi1 = service.getZiXunShiByWeight(null);
        List<Integer> str = new ArrayList<Integer>();
        for (int i = 0; i < getzixunshi1.size(); i++) {
            if (getzixunshi1.get(i).getQiandaoState().equals("已签到")) {//已经签到
                str.add(i, getzixunshi1.get(i).getId());
            } else {
                str.add(i,0);
            }
        }
        userquery.in("id", str);
        //获取已签到咨询师
        List<User> list = service.list(userquery);
        //判断是否存在已签到咨询师
        if (list.size() != 0) {
            //查询待分配，权重倒叙排列
            userquery.eq("is_config", "1");//1待分配
            userquery.orderByDesc("weight");
            userquery.last("limit 0 , 1");

            System.out.println(list);
            //获取咨询师为空的学生
            QueryWrapper<Student> stuquery = new QueryWrapper<Student>();
            stuquery.isNull("user_id");
            List<Student> list2 = stuService.list(stuquery);
            System.out.println(list2);
            List<User> userlist = null;
            int count = 0;//声明执行此操作的条数
            //遍历学生
            for (Student s : list2) {
                //获取待分配权重最大的用户（咨询师）
                userlist = service.list(userquery);
                System.out.println(userlist);
                //如果不存在已签到未分配的咨询师，设置所有签到咨询师为待分配
                if (userlist.size() == 0) {
                    service.updateBatchUser(str, 1);//1待分配,0已分配
                    //获取待分配权重最大的用户
                    userlist = service.list(userquery);
                }
                //给此用户分配权重最大的的咨询师
                User uu = userlist.get(0);
                s.setUserId(uu.getId());
                uu.setIsConfig("0");//已分配
                System.out.println(uu);
                service.update(uu, new QueryWrapper<User>().eq("id", uu.getId()));
                boolean update = stuService.update(s, new QueryWrapper<Student>().eq("id", s.getId()));
                if (update) {
                    count = count + 1;
                } else {
                    count = 0;
                }
            }
            System.out.println(count);
            System.out.println(list2.size());
            //批量设置学生咨询师
            if (list2.size()==0) {
                return new Result(2, "一键分配设置失败，暂时不存在待分配的学生");
            }
            if (count == list2.size()) {
                return new Result(0, "一键分配设置成功");
            } else {
                return new Result(1, "一键分配设置失败");
            }
        } else {
            return new Result(1, "一键分配设置失败，所有咨询师均未签到");
        }
    }


    /**
     * 手动分量设置
     * @param ids
     * @param uid
     * @return
     */
    @RequestMapping("/autoUser")
    public Object autoUser(String ids, Integer uid) {
        System.out.println(uid);
        System.out.println(ids);
        User user = new User();
        user.setId(uid);
        user.setIsConfig("0");
        service.updateById(user);
        boolean updateBatch = stuService.updateBatch(uid, ids);
        if (updateBatch) {
            return new Result(0, "分量成功");
        }
        return new Result(1, "分量失败");
    }

    /**
     * 修改学生信息
     *
     * @param id
     * @param student
     * @return
     */
    @PostMapping("/updateStudent")
    public Object updateStudent(@RequestParam Integer id, @Valid Student student) {
       /* List<Student> stuName = stuService.getStuName(student);
        if (stuName != null && stuName.size() > 0) {
            return new Result(2, "修改失败，该学生已存在,学生名称不能相同");
        }*/
        student.setId(id);
        boolean update = stuService.updateById(student);
        if (update) {
            return new Result(0, "修改成功");
        } else {
            return new Result(1, "修改失败");
        }
    }

    /**
     * 删除学生信息--软删除
     *
     * @param id
     * @return
     */
    @PostMapping("/delStudent")
    public Object delStudent(@RequestParam Integer id) {
        boolean ruanshan = stuService.ruanShanById(id);
        if (ruanshan) {
            return new Result(0, "删除成功");
        } else {
            return new Result(1, "删除失败");
        }
    }
}
